import sys
from PyQt5.QtWidgets import *
from UI_main import Ui_MainWindow
from PyQt5.QtWidgets import *
from Thread_fuse import thread_fuse
from MR_stitch_final import *
from PyQt5.QtGui import QTextDocument, QPixmap, QImage
from PyQt5.QtCore import QUrl,QBuffer, QByteArray,QIODevice,QDataStream, QObject
import base64
import numpy as np
from PIL import Image


class Main(QMainWindow):
    def __init__(self):
        super().__init__()
        self.__initData()
        self.__initUI()  # 界面绘制交给InitUi方法

    def __initData(self):
        self.sourcePath = ''
        self.consoleInfo = ''
        self.result = np.array([])

    def __initUI(self):
        self.UI = Ui_MainWindow()
        self.UI.setupUi(self)

    # 槽函数
    def on_ChooseSourcePath(self):
        dirpath = QFileDialog.getExistingDirectory(self, caption="选择源文件夹",
                                                   directory="./",
                                                   options=QFileDialog.ShowDirsOnly)
        print(dirpath)
        if dirpath == '':
            return
        self.sourcePath = dirpath
        self.UI.lineEdit_sourcePath.setText(dirpath)
        info = '选择源文件夹: '+dirpath
        self.__appendConsoleInfo(info)
        self.UI.pushButton_startFuse.setEnabled(True)

    def on_startFuse(self):
        # 调用孙哥写的线程
        self.UI.pushButton_chooseSourcePath.setEnabled(False)
        self.UI.pushButton_startFuse.setEnabled(False)
        self.UI.pushButton_reset.setEnabled(False)
        self.UI.pushButton_work_speed.setEnabled(True)
        self.UI.pushButton_result_display.setEnabled(True)
        self.thread_fuse = thread_fuse(str(self.UI.lineEdit_sourcePath.text()))
        self.thread_fuse.signal_info.connect(self.on_thread_info)
        # 注册一个新的信号槽函数来接收图像路径
        self.thread_fuse.signal_image.connect(self.display_image)
        self.thread_fuse.signal_finished.connect(self.on_thread_finished)
        self.thread_fuse.start()

    def on_reset(self):
        # 变量还原
        self.sourcePath = ''
        self.outputPath = ''
        self.consoleInfo = ''
        self.UI.qtextBrowser_console.setText(self.consoleInfo)

        self.UI.pushButton_chooseSourcePath.setEnabled(True)
        self.UI.pushButton_startFuse.setEnabled(False)
        self.UI.lineEdit_sourcePath.setText('')
        self.UI.pushButton_work_speed.setEnabled(False)
        self.UI.pushButton_result_display.setEnabled(False)

    def on_thread_info(self, info):
        self.__appendConsoleInfo(info)

    def on_thread_finished(self):
        self.UI.pushButton_reset.setEnabled(True)

    def display_image(self,result):
        # 将图像数据归一化到范围 [0, 1]
        img_normalized = result / np.max(result)
        # 将归一化后的图像数据转换为 uint8 类型
        img_uint8 = (img_normalized * 255).astype(np.uint8)
        height, width = img_uint8.shape
        qimage = QImage(img_uint8, width, height,QImage.Format_Grayscale8)  # 根据实际情况设置图片格式
        # 将 QImage 转换为 QByteArray
        byte_array = QByteArray()
        buffer = QBuffer(byte_array)
        buffer.open(QIODevice.WriteOnly)
        qimage.save(buffer, "PNG")
        # 将 QByteArray 转换为 base64 编码的字符串
        image_base64 = base64.b64encode(byte_array).decode("utf-8")
        # 构建 HTML 字符串
        self.html = f'<div align="center"> <img src="data:image/png;base64,{image_base64}" /> </div>'

    def result_display(self):
        self.UI.qtextBrowser_console.setHtml(self.html)
        self.UI.qtextBrowser_console.show()
    def work_speed(self):
        self.UI.qtextBrowser_console.setText(self.consoleInfo)

    # 私有函数
    def __appendConsoleInfo(self, info):
        self.consoleInfo += info + '\n'
        self.UI.qtextBrowser_console.setText(self.consoleInfo)

if __name__ == '__main__':
    # 创建应用程序和对象
    app = QApplication(sys.argv)
    main = Main()
    main.show()
    sys.exit(app.exec_())